var express = require('express');
var router = express.Router();
const UserModel = require('../../module/userModule');
const md5 = require('md5');

// 注册
router.get('/reg', function (req, res, next) {
    res.render('auth/reg');
});

router.post('/reg', function (req, res, next) {
    // 获取请求体中的数据
    UserModel.create({ ...req.body, password: md5(req.body.password) }).then((data) => {
        res.render('success', { msg: '注册成功', url: '/auth/login' });
    }, (err) => {
        res.json({
            code: "1002",
            msg: "注册失败",
            data: null,
        });
        return;
    })
});

// 登录
router.get('/login', function (req, res, next) {
    res.render('auth/login');
});

router.post('/login', function (req, res, next) {
    // 获取请求体中的数据
    let { username, password } = req.body;
    // 查询数据库
    UserModel.findOne({username, password: md5(password)}).then(data => {
        if (data) {
            // 设置session
            req.session.username = username;
            req.session.userid = data._id;

            // 登录成功
            res.render('success', { msg: '登录成功', url: '/account' });
        } else {
            // 登录失败
            res.status(401).send('用户名或者密码错误');
            return;
        }
    }, err => {
        // 查询失败
        res.status(500).send('查询失败');
        return;
    })
});

// 退出登录
router.post('/logout', function (req, res, next) {
    // 清除session
    req.session.destroy(() => {
        res.render('success', { msg: '退出成功', url: '/auth/login' });
    })
});

module.exports = router;
